package com.org.oracle.controller;

import cn.hutool.core.io.FileUtil;
import com.org.oracle.enums.ResponseCodeEnum;
import com.org.oracle.mysql.entity.Questions;
import com.org.oracle.result.Result;
import com.org.oracle.service.FileService;
import com.org.oracle.service.QuestionsService;
import com.org.oracle.util.FileUploadUtils;
import jakarta.annotation.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author: heiye
 * @date: 2024/12/10 下午12:35
 * @version: v1.0.0
 * @description: 对象存储
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private FileService fileService;

    @Resource
    private QuestionsService questionsService;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @PostMapping(value = "/upload/image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result upload(@RequestParam(value = "file") MultipartFile file) {
        return Result.ok(fileService.uploadImg(file));
    }

    @PostMapping("/uploadCsv")
    public Result uploadCsv(@RequestParam("file") MultipartFile file) throws IOException {
        //获取原文件名
        String originalFileName = file.getOriginalFilename();
        //提取文件后缀
        String fileExtension;
        if (originalFileName != null) {
            fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        }else{
            //校验文件类型为空的情况
            return Result.fail("文件名不为空",ResponseCodeEnum.QUESTION_UPLOAD_FILENAME_NOTNULL.getCode());
        }
        // 文件类型校验
        if (!FileUploadUtils.isValidCSVFileType(file)) {
            return Result.fail("文件类型错误，必须为CSV格式", ResponseCodeEnum.QUESTION_UPLOAD_ERROR_CSV.getCode());
        }
        //使用UUID生成文件名
        String uniqueFile = UUID.randomUUID() + fileExtension;
        // 获取文件的字节数据并保存到服务器临时路径
        String tempFilePath = FileUtil.getTmpDirPath() + uniqueFile;
        file.transferTo(new File(tempFilePath));

        // 解析 CSV 文件
        List<Questions> questions = fileService.parseCsv(tempFilePath);

        // TODO 先关了保存到数据库
//        questionsService.saveQuestions(questions);
        //删除处理成功的文件
        File tempFile = new File(tempFilePath);
        if (tempFile.exists()) {
            if (tempFile.delete()) {
                System.out.println("临时文件已成功删除：" + tempFilePath);
            } else {
                System.out.println("无法删除临时文件：" + tempFilePath);
            }
        }
        return Result.ok();
    }

    @PostMapping("/uploadExcel")
    public Result uploadExcel(@RequestParam("file") MultipartFile file) throws IOException {
        //获取原文件名
        String originalFileName = file.getOriginalFilename();
        //提取文件后缀
        String fileExtension;
        if (originalFileName != null) {
            fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        }else{
            //校验文件类型为空的情况
            return Result.fail("文件名不为空",ResponseCodeEnum.QUESTION_UPLOAD_FILENAME_NOTNULL.getCode());
        }
        // 校验文件类型
        if (!FileUploadUtils.isValidExcelFileType(file)) {
            return Result.fail("文件类型错误，必须为Excel格式",ResponseCodeEnum.QUESTION_UPLOAD_ERROR_EXCEL.getCode());
        }
        //使用UUID生成文件名
        String uniqueFile = UUID.randomUUID() + fileExtension;
        // 获取文件的字节数据并保存到服务器临时路径
        // TODO 生产环境，能否正常运行？
        String tempFilePath = FileUtil.getTmpDirPath() + uniqueFile;
        file.transferTo(new File(tempFilePath));
        try {
            // 解析 Excel 文件
            List<Questions> questions = fileService.parseExcel(tempFilePath);
            // TODO 先关了保存到数据库
//            questionsService.saveQuestions(questions);
        } catch (IllegalArgumentException e) {
            return Result.fail("Excel 文件格式不正确：" + e.getMessage(),ResponseCodeEnum.QUESTION_UPLOAD_ERROR_EXCEL.getCode());
        }
        //删除处理成功的文件
        File tempFile = new File(tempFilePath);
        if (tempFile.exists()) {
            if (tempFile.delete()) {
                System.out.println("临时文件已成功删除：" + tempFilePath);
            } else {
                System.out.println("无法删除临时文件：" + tempFilePath);
            }
        }
        return Result.ok();
    }
}
